package com.orange.cepmanager.android.listener;



import java.util.List;

import android.content.Context;
import android.location.Address;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

import com.orange.cepmanager.android.CEPManagerCommon;
import com.orange.cepmanager.android.ngsi.events.Event;
import com.orange.cepmanager.android.service.Service;
import com.orange.cepmanager.android.tools.GpsLocation;


public class LocationListener extends Listener implements
    android.location.LocationListener {
	public static final String TAG = CEPManagerCommon.LOCATION_LISTENER_TAG;
  private static LocationManager manager;
  private static List<String> locationProviders;
  private Context context;

	public void onLocationChanged(final Location location) {
		final Service service = Service.getInstance();
		final Event event = new Event();
		event.eventType = CEPManagerCommon.EVENT_TYPE_LOCATION;
		final StringBuilder sb = new StringBuilder();
		sb.append("latitude:");
		sb.append(location.getLatitude());
		sb.append(",longitude:");
		sb.append(location.getLongitude());
		Address adr = GpsLocation.getGpsLocationFromCoordinates(
				location.getLatitude(), location.getLongitude());
		// event.params = sb.toString();
		event.params = adr.getThoroughfare() + ", zip code : "
				+ adr.getPostalCode() + " " + adr.getLocality()
				+ ", department : " + adr.getSubAdminArea() + ", Country : "
				+ adr.getCountryName() + " , latitude : " + adr.getLatitude()
				+ ", longitute : " + adr.getLongitude();
		service.acceptIncomingEvent(event);
	}

  public void onProviderDisabled(final String provider) {
    // Do nothing
  }

  public void onProviderEnabled(final String provider) {
    // Do nothing
  }

  public void onStatusChanged(final String provider, final int status,
      final Bundle extras) {
    // Do nothing
  }

  @Override
  protected boolean registerImpl(final Context context) {
    if (!Service.checkPermissions(context, new String[] {
        android.Manifest.permission.ACCESS_COARSE_LOCATION,
        android.Manifest.permission.ACCESS_FINE_LOCATION }))
      return false;
    manager = (LocationManager) context
        .getSystemService(Context.LOCATION_SERVICE);
    locationProviders = manager.getAllProviders();
    for (final String provider : locationProviders) {
      Log.v(TAG, "register location provider : " + provider);
      manager.requestLocationUpdates(provider, CEPManagerCommon.LOCATION_MIN_UPDATE_TIME,
    		  CEPManagerCommon.LOCATION_MIN_UPDATE_DISTANCE, this);
    }
    return true;
  }

  @Override
  protected boolean unregisterImpl(final Context context) {
    if (manager != null) {
      manager.removeUpdates(this);
      return true;
    }
    return false;
  }
}
